package com.Siven.view;

import java.text.SimpleDateFormat;
import java.util.Date;

import com.Siven.refreshlistview_library.R;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

/**
 * 
 * @author 留得残荷听雨声
 * @2016-8-4下午10:51:05
 * @描述 自定义的listview，加上下拉刷新，上拉加载个更多 以及其他功能的实现
 * 
 */
public class RefreshListView extends ListView {

	private LinearLayout		head;
	private View				root;
	private LinearLayout		ll_listviews_head_root;
	private int					Headhight;
	private int					footHight;
	private float				downY;
	private int					listViewOnScreanY;
	private View				lunBoTu;

	private final int			PULL_DOWN		= 1;			// 下拉刷新状态
	private final int			RELEASE_STATE	= 2;			// 松开刷新
	private final int			REFRESHING		= 3;			// 正在刷新
	private int					currentState	= PULL_DOWN;	// 当前的状态
	private TextView			tv_state;
	private TextView			tv_time;
	private ProgressBar			pb_uploding;
	private ImageView			iv_arrow;
	private RotateAnimation		up_ra;
	private RotateAnimation		down_ra;
	private OnRefreshDataLister	onRefreshDataLister;

	private boolean				isEnableRefresh;				// 是否使用下拉刷新
	private boolean				isEnableLoadingMore;			// 是否使用头尾加载更多
	private boolean				isMoreUploading=false;

	public RefreshListView(Context context, AttributeSet attrs, int defStyle){
		super(context, attrs, defStyle);
		initView();
		inEvent();
		initAnimation();
	}

	public RefreshListView(Context context, AttributeSet attrs){
		this(context, attrs, 0);
	}

	public RefreshListView(Context context){
		this(context, null);
	}

	private void initView() {
		initFoot();
		initHead();
	}

	private void inEvent() {
		setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if(!isEnableLoadingMore){
					return;
				}
				
				if (getLastVisiblePosition() == getAdapter().getCount() - 1) {
					root.setPadding(0, 0, 0, 0);
					setSelection(getAdapter().getCount());

					isMoreUploading = true;
					if (onRefreshDataLister != null) {
						onRefreshDataLister.refreshMore();
					}
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {

			}
		});
	}

	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		switch (ev.getAction()) {
			case MotionEvent.ACTION_DOWN:// 倍按下
				downY = ev.getY();
				break;

			case MotionEvent.ACTION_MOVE:

				if (!isEnableRefresh) {
					break;
				}
				if (currentState == REFRESHING) {
					break;
				}
				if (!isFullLunBoTu()) {
					break;
				}

				if (downY == -1) {
					downY = ev.getY();
				}
				float moveY = ev.getY();
				float dy = moveY - downY;

				if (dy > 0 && getFirstVisiblePosition() == 0) {
					float refreshHeadhight = -Headhight + dy;
					if (refreshHeadhight < 0 && currentState != PULL_DOWN) {
						// 刷新還沒有完全顯示
						// 处于下拉刷新状态
						currentState = PULL_DOWN;
						refreshState();
					} else if (refreshHeadhight >= 0
							&& currentState != RELEASE_STATE) {
						// 处于松开刷新状态
						currentState = RELEASE_STATE;
						refreshState();
					}
					ll_listviews_head_root.setPadding(0,
							(int) refreshHeadhight, 0, 0);
					return true;
				}
				break;
			case MotionEvent.ACTION_UP:
				downY = -1;
				if (currentState == PULL_DOWN) {
					ll_listviews_head_root.setPadding(0, -Headhight, 0, 0);
				} else if (currentState == RELEASE_STATE) {
					ll_listviews_head_root.setPadding(0, 0, 0, 0);
					currentState = REFRESHING;
					refreshState();
					if (onRefreshDataLister != null) {
						System.out.println(onRefreshDataLister+"-------");
						onRefreshDataLister.refreshData();
					}
				}

				break;
		}
		return super.onTouchEvent(ev);
	}

	private void refreshState() {
		switch (currentState) {
			case PULL_DOWN:
				tv_state.setText("下拉刷新");
				iv_arrow.startAnimation(down_ra);
				break;

			case RELEASE_STATE:
				tv_state.setText("松开刷新");
				iv_arrow.startAnimation(up_ra);

				break;
			case REFRESHING:
				iv_arrow.clearAnimation();// 清除所有的动画
				pb_uploding.setVisibility(View.VISIBLE);
				iv_arrow.setVisibility(View.GONE);
				tv_state.setText("正在刷新数据");
				
				break;
			default:
				break;
		}

	}

	private void initAnimation() {
		up_ra = new RotateAnimation(0, -180, Animation.RELATIVE_TO_SELF, 0.5f,
				Animation.RELATIVE_TO_SELF, 0.5f);
		up_ra.setDuration(500);
		up_ra.setFillAfter(true);// 停留在动画结束的状态

		down_ra = new RotateAnimation(-180, -360, Animation.RELATIVE_TO_SELF,
				0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
		down_ra.setDuration(500);
		down_ra.setFillAfter(true);// 停留在动画结束的状态
	}

	public void setOnRefreshListener(OnRefreshDataLister onRefreshDataLister) {
		this.onRefreshDataLister = onRefreshDataLister;
	}

	public interface OnRefreshDataLister {

		void refreshData();

		void refreshMore();
	}

	// 在刷新完成的时候调用的方法
	public void refreshFinish() {
		if (isMoreUploading) {
			// 加载更多数据
			isMoreUploading = false;
			// 隐藏加载更多数据的组件
			root.setPadding(0, -footHight, 0, 0);
		} else {
			tv_state.setText("下拉刷新");
			pb_uploding.setVisibility(View.INVISIBLE);
			iv_arrow.setVisibility(View.VISIBLE);
			tv_time.setText(getCurrentFormatDate());
			ll_listviews_head_root.setPadding(0, -Headhight, 0, 0);

			currentState = PULL_DOWN;
		}
	}

	// 得到当前的时间
	private String getCurrentFormatDate() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return format.format(new Date());
	}

	private boolean isFullLunBoTu() {
		// 判断轮播图是否完全显示

		if(lunBoTu==null){
			return true;
		}
		int[] location = new int[2];
		// 如果轮播图没有完全显示，相应的是Listview的事件
		// 判断轮播图是否完全显示
		// 取listview在屏幕中坐标 和 轮播图在屏幕中的坐标 判断
		// 取listview在屏幕中坐标
		if (listViewOnScreanY == 0) {
			this.getLocationOnScreen(location);
			// 获取listview在屏幕中的y轴坐标
			listViewOnScreanY = location[1];
		}

		// 轮播图在屏幕中的坐标
		lunBoTu.getLocationOnScreen(location);
		// 判断
		if (location[1] < listViewOnScreanY) {
			// 轮播图没有完全显示
			// 继续相应listview的事件
			// System.out.println("没有显示");
			return false;
		}
		return true;
	}

	/**
	 * 加载尾部布局
	 */
	private void initFoot() {
		root = View.inflate(getContext(), R.layout.listnews_refresh_foot, null);

		root.measure(0, 0);
		footHight = root.getMeasuredHeight();

		root.setPadding(0, -footHight, 0, 0);
		addFooterView(root);
	}

	/**
	 * 加载头部布局
	 */
	private void initHead() {
		head = (LinearLayout) View.inflate(getContext(),
				R.layout.listview_head_container, null);
		ll_listviews_head_root = (LinearLayout) head
				.findViewById(R.id.ll_listview_head_root);

		tv_state = (TextView) head
				.findViewById(R.id.tv_listview_head_state_dec);
		tv_time = (TextView) head
				.findViewById(R.id.tv_listview_head_refresh_time);
		pb_uploding = (ProgressBar) head
				.findViewById(R.id.pb_listview_head_loading);
		iv_arrow = (ImageView) head.findViewById(R.id.iv_listview_head_arrow);

		ll_listviews_head_root.measure(0, 0);
		Headhight = ll_listviews_head_root.getMeasuredHeight();
		ll_listviews_head_root.setPadding(0, -Headhight, 0, 0);
		addHeaderView(head);
	}

	//是否使用头刷新
	public void setIsRefresh(boolean isRefresh) {
		this.isEnableRefresh = isRefresh;
	}

	//是否使用尾加载更多
	public void setIsLoadingMore(boolean isLoadingMore) {
		this.isEnableLoadingMore = isLoadingMore;
	}

	public void addLunBoPic(View view) {

		if (isEnableRefresh) {
			lunBoTu = view;
			head.addView(view);
		} else {
			super.addHeaderView(view);
		}
	}
}
